package com.yxw.common.utils;

import io.jsonwebtoken.*;
import org.springframework.util.StringUtils;

import java.util.Date;
/**
 * @className: com.yxw.common.utils.JwtHelper
 * @description: 生成JSON Web令牌的工具类
 * @author: tommy
 * @create: 2023-07-30 下午 07:07
 */

public class JwtHelper {
    //token过期时间
    private static long tokenExpiration = 365 * 24 * 60 * 60 * 1000;
    //加密秘钥
    private static String tokenSignKey = "123456";
    //根据用户id和用户名称生成token字符串
    public static String createToken(String userId, String username) {
        String token = Jwts.builder()
                .setSubject("AUTH-USER")//分组
                .setExpiration(new Date(System.currentTimeMillis() + tokenExpiration))//设置过期时间
                //有效载荷
                .claim("userId", userId)
                .claim("username", username)
                //编码加密处理
                .signWith(SignatureAlgorithm.HS512, tokenSignKey)
                .compressWith(CompressionCodecs.GZIP)//压缩
                .compact();
        return token;
    }
    //从token字符串中获取userid
    public static String getUserId(String token) {
        try {
            if (StringUtils.isEmpty(token)) { return null;}

            Jws<Claims> claimsJws = Jwts.parser().setSigningKey(tokenSignKey).parseClaimsJws(token);
            Claims claims = claimsJws.getBody();
            String userId = (String) claims.get("userId");
            return userId;
        } catch (Exception e) {
            e.printStackTrace();
            return null;
        }
    }
    //从token字符串中获取username
    public static String getUsername(String token) {
        try {
            if(StringUtils.isEmpty(token)){ return "";}

            Jws<Claims> claimsJws = Jwts.parser().setSigningKey(tokenSignKey).parseClaimsJws(token);
            Claims claims = claimsJws.getBody();
            return (String) claims.get("username");
        } catch (Exception e) {
            e.printStackTrace();
            return null;
        }
    }

    public static void main(String[] args) {
        //eyJhbGciOiJIUzUxMiIsInppcCI6IkdaSVAifQ.H4sIAAAAAAAAAKtWKi5NUrJScgwN8dANDXYNUtJRSq0oULIyNLM0MrQwNzI11FEqLU4t8kwBikGYeYm5qUAtlRXlSrUAaa2m30AAAAA.qijL-nmCta27qThJ4Yui-Unb5MUG670v2c3B3nib740Pn1oCwrRyMciz8F45eEhkV6OO7PCHClzDaSqCnPIKpg
        String token = JwtHelper.createToken("1", "admin");
        System.out.println(token);
        String userId = JwtHelper.getUserId(token);
        System.out.println(userId);

        String username = JwtHelper.getUsername(token);
        System.out.println(username);
    }
}